﻿using System;
using System.Collections.Generic;
using MugenInjection.Infrastructure;
using MugenInjection.Interface;

namespace MugenInjection.Scope
{
    /// <summary>
    ///     Represents the weak reference scope lifecycle.
    /// </summary>
    public class WeakReferenceScopeLifecycle : ScopeLifecycleBase
    {
        #region Fields

        private WeakReference _weakReference;

        #endregion

        #region Overrides of ScopeLifecycleBase

        /// <summary>
        ///     Resolves instance for the specified <see cref="IBindingContext" /> from scope.
        /// </summary>
        /// <returns>An instance of the service.</returns>
        protected override object GetObjectFromScope()
        {
            object service = null;
            if (_weakReference == null)
            {
                lock (Locker)
                {
                    if (_weakReference == null)
                    {
                        service = ResolveCurrentService();
                        if (service == null)
                            return null;
                        _weakReference = new WeakReference(service);
                    }
                }
            }
            else
            {
                service = _weakReference.Target;
                if (service == null)
                {
                    lock (Locker)
                    {
                        service = _weakReference.Target;
                        if (service == null)
                        {
                            service = ResolveCurrentService();
                            if (service == null)
                                return null;
                            _weakReference = new WeakReference(service);
                        }
                    }
                }
            }
            return service;
        }

        /// <summary>
        ///     Gets all created objects in the current scope.
        /// </summary>
        protected override IList<object> GetObjectsFromScope()
        {
            object service = null;
            if (_weakReference != null)
                service = _weakReference.Target;
            if (service == null)
                return InjectorUtilsInternal.EmptyParams;
            return new[] {service};
        }

        /// <summary>
        ///     Clears the current scope.
        /// </summary>
        protected override void ClearScope()
        {
            _weakReference = null;
        }

        #endregion
    }
}